/**
 * 数据库初始化脚本
 */
require('dotenv').config();
const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 读取 SQL 文件内容
const sqlFilePath = path.join(__dirname, 'createDatabase.sql');
const sqlContent = fs.readFileSync(sqlFilePath, 'utf8');

// 分割 SQL 语句
const sqlStatements = sqlContent
  .split(';')
  .filter(statement => statement.trim().length > 0)
  .map(statement => statement.trim() + ';');

async function initDatabase() {
  console.log('开始初始化数据库...');
  
  // 创建数据库连接
  const connection = await mysql.createConnection({
    host: process.env.DB_HOST || 'localhost',
    port: process.env.DB_PORT || 3306,
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || 'mysql520',
    multipleStatements: true
  });
  
  try {
    console.log('连接数据库成功');
    
    // 执行 SQL 语句
    for (const statement of sqlStatements) {
      console.log(`执行 SQL: ${statement.substring(0, 50)}${statement.length > 50 ? '...' : ''}`);
      await connection.query(statement);
    }
    
    console.log('数据库初始化完成');
  } catch (error) {
    console.error('数据库初始化失败:', error);
    process.exit(1);
  } finally {
    await connection.end();
  }
}

// 执行初始化
initDatabase(); 